<template>
	<div class="scheduleBox">
		<div class="left">
			<el-calendar v-model="dateValue">
				<template #date-cell="{ data }">
					<p :class="data.isSelected ? 'is-selected' : ''">
						{{ data.day.split('-').slice(1).join('-') }}
					</p>
				</template>
			</el-calendar>
		</div>
		<div class="right">
			<div class="tab">
				<el-date-picker
					v-model="dateValue"
					type="date"
					placeholder="日期"
					:clearable="false"
				/>
				<el-tabs v-model="activeName" class="tabs">
					<el-tab-pane label="日程管理" name="rcgl">
						<div class="schedulist" v-loading="loadingSchedu">
							<div v-for="(item, index) in scheduleList" class="item" @click="rcglClick(item)">
								<div>
									<span>{{ item.content }}</span>
									<span>{{ item.scheduleTag }}</span>
								</div>
								<div>{{ item.startDate }} {{ item.start }}-{{ item.end }}</div>
							</div>
							<el-empty
								description="暂无数据"
								v-show="scheduleList.length == 0&&!loadingSchedu"
							/>
						</div>
					</el-tab-pane>
					<el-tab-pane label="团队日程" name="tdrc">
            <div class="memberBox">
              <div class="title">研究员</div>
              <span class="items">
                <template v-for="item in props.teamList">{{ item.fUserName }}、</template>
              </span>
              <div class="btn" @click="emit('showTeam')">+</div>
            </div>
            <div class="schedulist" v-loading="loadingSchedu">
							<div v-for="(item, index) in scheduleList" class="item">
								<div>
									<span>{{ item.content }}</span>
									<span>{{ item.scheduleTag }}</span>
								</div>
								<div>{{ item.startDate }} {{ item.start }}-{{ item.end }}</div>
							</div>
							<el-empty
								description="暂无数据"
								v-show="scheduleList.length == 0&&!loadingSchedu"
							/>
						</div>
          </el-tab-pane>
					<el-tab-pane label="研究员日程" name="yjyrc"> </el-tab-pane>
				</el-tabs>
				<div @click.stop="showaddSchedule" class="add" v-if="useTokenStore().isLoggedIn">+ 添加日程</div>
			</div>
		</div>
		<AddMyScheduleDialog ref="addMyScheduleDialog" :defaultDate="dateValue" @onConfirm="updateData" />
    
	</div>
</template>
<script setup lang="ts">
import { formatDateTime } from '@/miniFile/utils/util'
import AddMyScheduleDialog from './AddMyScheduleDialog.vue'
import { request } from '@/utils/request'
import { computed, nextTick, onMounted, ref, watch } from 'vue'
import { useTokenStore } from '@/store/modules/tokenStore'

const addMyScheduleDialog = ref()
const dateValue = ref(new Date())
const activeName = ref('rcgl')
const scheduleList = ref([])
const loadingSchedu = ref(false)
interface Props {
	userInfo: any
	powers: string
	scheduleList: any[]
	teamList: any[]
	riliList: any[]
	addTime: string
}
const props = defineProps<Props>()
watch(
	[() => dateValue.value, () => activeName.value],
	() => {
    if (!useTokenStore().isLoggedIn) {
      return
    }
		if (activeName.value == 'rcgl') {
			getSchedule()
		} else if (activeName.value == 'tdrc') {
			getTeamSchedule()
		}
	},
	{
		immediate: true,
	}
)
const emit = defineEmits(['showTeam'])
const researcherIds = computed(() => {
	const result = []
  
	props.teamList.forEach((item: any) => {
		if (item.checked && item.fUserId != 0) {
			result.push(item.fUserId)
		}
	})
  console.log('researcherIds',result);
	return result
})
function timestamp() {
	const active = new Date(dateValue.value)
  active.setHours(0,0,0,0)
  return Math.floor(active.getTime())
}
// 格式化我的日程项目
const formatMyScheduleItem = (item: any) => {
	const startDate = formatDateTime(item.customStart, 'yyyy/MM/dd hh:mm')
	const endDate = formatDateTime(item.customEnd, 'yyyy/MM/dd hh:mm')
	const start = formatDateTime(item.customStart, 'hh:mm')
	const end = formatDateTime(item.customEnd, 'hh:mm')
	const isToday =
		formatDateTime(item.customStart, 'yyyy/MM/dd') ===
		formatDateTime(item.customEnd, 'yyyy/MM/dd')

	return {
		id: item.id,
		contentId: item.contentId,
		content: item.content,
		start,
		end,
		scheduleType: item.scheduleType,
		scheduleClassify: item.scheduleClassify,
		scheduleTag: item.scheduleTag || '',
		place: item.place,
		customStart: startDate,
		endDate,
		customer: item.customer,
		contact: item.contact,
		startDate: item.startDate,
		customEnd: item.customEnd,
		isLock: item.lock,
		isMine: true,
		isToday,
	}
}
async function getSchedule() {
	try {
    
		scheduleList.value = []
		loadingSchedu.value = true
		const response = await request.post(
			'/wxapi/appletApi/public/schedule/getMyScheduleList',
			{ startTime: timestamp() }
		)
		loadingSchedu.value = false
		console.log('response', response)

		const res = response.data

		if (res.code === 1 && res.data && res.data.length) {
			const result = res.data.map((item: any) => formatMyScheduleItem(item))
			scheduleList.value = JSON.parse(JSON.stringify(result))
		} else {
			scheduleList.value = []
		}
	} catch (error) {
		console.error('获取日程失败:', error)
		scheduleList.value = []
	}
}
// 格式化团队日程项目
const formatTeamScheduleItem = (item: any, userId: string) => {
	const startTime = formatDateTime(item.customStart, 'yyyy-MM-dd hh:mm')
	const endTime = formatDateTime(item.customEnd, 'yyyy-MM-dd hh:mm')
	const startDate = formatDateTime(item.customStart, 'yyyy/MM/dd hh:mm')
	const endDate = formatDateTime(item.customEnd, 'yyyy/MM/dd hh:mm')
	const start = formatDateTime(item.customStart, 'hh:mm')
	const end = formatDateTime(item.customEnd, 'hh:mm')
	const isToday =
		formatDateTime(item.customStart, 'yyyy/MM/dd') ===
		formatDateTime(item.customEnd, 'yyyy/MM/dd')

	let reservationUsers = []
	if (
		item.reservationInfo &&
		item.reservationInfo.reservationUsers &&
		item.reservationInfo.reservationUsers.length
	) {
		reservationUsers = item.reservationInfo.reservationUsers.map((itm: any) => {
			if (itm.reserveStatus == 0) {
				itm.reserveStatusName = '待通过'
				itm.color = '#4097FF'
			} else if (itm.reserveStatus == 1) {
				itm.reserveStatusName = '预约通过'
				itm.color = '#52C41A'
			} else if (itm.reserveStatus == 2) {
				itm.reserveStatusName = '预约失败'
				itm.color = '#FF4D4F'
			} else if (itm.reserveStatus == 3) {
				itm.reserveStatusName = '已转介'
				itm.color = '#4097FF'
			} else if (itm.reserveStatus == 4) {
				itm.reserveStatusName = '未参加'
				itm.color = '#999'
			} else if (itm.reserveStatus == 5) {
				itm.reserveStatusName = '终止'
				itm.color = '#FF4D4F'
			}
			return { ...itm }
		})
	}

	return {
		id: item.id,
		contentId: item.contentId,
		reservationUsers,
		scheduleType: item.scheduleType,
		content: item.content,
		place: item.place,
		customer: item.customer,
		contact: item.contact,
		researcherName: item.researcherName ? item.researcherName : '',
		managerName: item.reservationInfo ? item.reservationInfo.managerName : '',
		theme: item.reservationInfo ? item.reservationInfo.theme : '',
		startTime,
		endTime,
		start,
		end,
		startDate:item.startDate,
		endDate,
		customStart: item.customStart,
		customEnd: item.customEnd,
		isLock: item.lock,
		isMine: false,
		isToday,
	}
}
const getTeamSchedule = async () => {
	try {
		loadingSchedu.value = true
		const response = await request.post(
			'/wxapi/appletApi/schedule/getTeamSchedule',
			{
				startTime: timestamp(),
				offset: 1,
				researcherIds: researcherIds.value,
			}
		)
		loadingSchedu.value = false

		const res = response.data
      
		if (res.code === 1 && res.data && res.data.length) {
			const result = res.data.map((item: any) =>
				formatTeamScheduleItem(item, useTokenStore().userInfo.userId)
			)
			scheduleList.value = JSON.parse(JSON.stringify(result))
		} else {
			scheduleList.value = []
		}
	} catch (error) {
		console.error('获取团队日程失败:', error)
		scheduleList.value = []
	}
}
function rcglClick(item:any) {
  addMyScheduleDialog.value.showDialog('edit',item)
}
function showaddSchedule() {
	addMyScheduleDialog.value.showDialog('add')
}
function updateData() {
  if (activeName.value == 'rcgl') {
			getSchedule()
		} else if (activeName.value == 'tdrc') {
			getTeamSchedule()
		}
}


onMounted(() => {})
defineExpose({
  getTeamSchedule
})
</script>
<style scoped lang="less">
.scheduleBox {
	display: flex;
	.left {
		width: 30%;
		min-width: 400px;
	}
	.right {
		flex: 1;
		.tab {
			position: relative;
		}
	}
}
.schedulist {
	min-height: 500px;
	.item {
		font-size: 14px;
		padding: 10px 20px;
		background-color: rgba(198, 95, 239, 0.3);
		border-radius: 5px;
		margin-bottom: 10px;
		> div:nth-child(1) {
			display: flex;
			justify-content: space-between;
		}
	}
}
.memberBox {
  display: flex;
  position: relative;
  align-items: center;
  margin-bottom: 5px;
  font-size: 16px;
  .title {
    width: 80px;
    color: rgb(170, 170, 170);
  }
  .items {
    
      max-width: 37.5rem;
    white-space: nowrap;      /* 强制文本不换行 */
    overflow: hidden;         /* 隐藏超出部分 */
    text-overflow: ellipsis;  /* 超出部分显示省略号 */
    color: rgb(75, 75, 75);
  }
  .btn {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 20px;
    height: 20px;
    border-radius: 50%;
    font-size: 16px;
    font-weight: 600;
    color: rgb(42, 109, 255);
    border: 2px solid rgb(42, 109, 255);
    position: absolute;
    right: 10px;
    cursor: pointer;
    user-select: none;
    &:active {
      transform: translate(1px,1px);
    }
  }
}
.add {
	cursor: pointer;
	display: flex;
	align-items: center;
	justify-content: center;
	border-radius: 5px;
	padding: 5px 8px;
	position: absolute;
	right: 0;
	top: 0;
	background-color: #ccc;
	border: 1px solid #ccc;
	font-size: 12px;
}
:deep(.el-calendar) {
	font-size: 14px;
}
:deep(.el-tabs__header) {
  margin: 0 0 5px;
}
@media (max-width: 920px) {
	.left {
		display: none;
	}
}
</style>
